//
//  UserRegistionViewController.swift
//  SitPosition
//
//  Created by apple on 2018/12/31.
//  Copyright © 2018 apple. All rights reserved.
//

import Foundation
import UIKit
import Cartography

class UserRegistionViewController : UserLoginRegistrationBaseViewController {
    
    // MARK: - Properties

    // 注册成功回调
    var successCallback: VoidCallback = { }

    // 验证码
    static fileprivate var verifyCode: PhoneVerifyCode? = nil
    
    // MARK: - Subviews
    
    // 手机号
    lazy var phoneTextfield: TextFieldWithLRView = {
        return _buildTextField(placeholder: Strings.logonPhonePlaceholder,
                               leftView: UIImageView(image: UIImage(named: "logon_phone")))
    }()
    
    // 验证码
    lazy var verifyCodeTextfield: TextFieldWithLRView = {
        return _buildTextField(placeholder: Strings.logonVerifyCodePlaceholder,
                               leftView: UIImageView(image: UIImage(named: "logon_key")))
    }()
    
    // 邀请码
    lazy var invitCodeTextfield: TextFieldWithLRView = {
        return _buildTextField(placeholder: Strings.logonInputInvitCode)
    }()
    
    // 下一步按钮
    lazy var nextButton: UserLogonStateButton = {
        let button = UserLogonStateButton(title: Strings.logonNext)
        button.addTarget(self, action: #selector(_step2Next), for: UIControl.Event.touchUpInside)
        return button
    }()
    
    let seperator1 = UIView.colored(Theme.Color.primaryBlueSeperatorColor)
    let seperator2 = UIView.colored(Theme.Color.primaryBlueSeperatorColor)
    let seperator3 = UIView.colored(Theme.Color.primaryLightTextColor)
    
    // MARK: - Object lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        gk_navLeftBarButtonItem = UIBarButtonItem(imageName: "ic_nav_back", target: self, action: #selector(_backButtonTapped))
        
        // 设置Views
        view.addSubviews([
            titleLabel,
            phoneTextfield,
            seperator1,
            verifyCodeTextfield,
            getVerifyCodeButton,
            seperator2,
            invitCodeTextfield,
            nextButton,
            seperator3,
            bodyIV
        ])
        _setupContraints()
        
        // 初始化Views
        titleLabel.text = Strings.logonRegister
        getVerifyCodeButton.addTarget(self, action: #selector(_getVerifyCode), for: UIControl.Event.touchUpInside)
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return UIStatusBarStyle.lightContent
    }
    
}

// MARK: - Private Methods

extension UserRegistionViewController {
    
    // 设置视图约束
    func _setupContraints() {
        // titleLabel
        constrain(titleLabel, gk_navigationBar, view) { v, sibling, parent in
            v.top == sibling.bottom + 34
            v.left == parent.left + 40
            v.right == parent.right - 40
            v.height == 25
        }
        
        // phoneTextfield
        let kTextfieldHeight: CGFloat = 36
        constrain(phoneTextfield, titleLabel) { v, sibling in
            v.top == sibling.bottom + 48
            v.left == sibling.left
            v.height == kTextfieldHeight
            v.right == sibling.right
        }
        
        // seperator1
        constrain(seperator1, phoneTextfield) { v, sibling in
            v.top == sibling.bottom+4
            v.left == sibling.left
            v.right == sibling.right
            v.height == 1
        }
        
        // verifyCodeTextfield
        constrain(verifyCodeTextfield, seperator1) { v, sibling in
            v.top == sibling.bottom + 37
            v.left == sibling.left
            v.height == kTextfieldHeight
            v.right == sibling.right - 110
        }
        
        // seperator2
        constrain(seperator2, verifyCodeTextfield) { v, sibling in
            v.top == sibling.bottom + 4
            v.left == sibling.left
            v.right == sibling.right
            v.height == 1
        }
        
        // getVerifyCodeButton
        constrain(getVerifyCodeButton, seperator1, seperator2) { v, sibling, sibling2 in
            v.right == sibling.right
            v.bottom == sibling2.bottom
            v.width == 80
            v.height == 35
        }
        
        // invitCodeTextfield†
        constrain(invitCodeTextfield, seperator2, view) { v, sibling, parent in
            v.top == sibling.bottom + 57
            v.left == sibling.left
            v.height == kTextfieldHeight
            v.right == parent.right - 205
        }
        
        // seperator3
        constrain(seperator3, invitCodeTextfield) { v, sibling in
            v.top == sibling.bottom + 4
            v.left == sibling.left
            v.right == sibling.right
            v.height == 1
        }
        
        // nextButton
        constrain(nextButton, seperator1, seperator3) { v, sibling, sibling2 in
            v.right == sibling.right
            v.bottom == sibling2.bottom
            v.width == 150
            v.height == 55
        }
        
        // bodyIV
        constrain(bodyIV, nextButton, view) { v, sibling, parent in
            v.top <= sibling.bottom + 45 ~ .defaultLow
            v.left == parent.left
            v.right == parent.right
            v.bottom == parent.bottom
        }
    }
    
    // 返回按钮点击事件
    @objc func _backButtonTapped() {
        backCallback()
    }
    
    // 获取验证码
    @objc func _getVerifyCode() {
        // 校验参数
        let cs: CharacterSet = CharacterSet.whitespacesAndNewlines
        guard let mobile = phoneTextfield.text?.trimmingCharacters(in: cs), !mobile.isEmpty else {
            view.makeToast(Strings.logonPhoneEmpty)
            return
        }
        
        // 获取验证码
        view.makeToastActivity(.center)
        NetworkClient.instance.fetchVerifyCode(mobile: mobile, type: "register", success: { [weak self] (data) in
            guard let sself = self else { return }
            sself.view.hideToastActivity()
            
            guard let data_ = data else {
                sself.view.makeToast(Strings.logonFailedSendPhoneCode)
                return
            }
            do {
                let decoder: JSONDecoder = JSONDecoder()
                let verifyCode: PhoneVerifyCode = try decoder.decode(PhoneVerifyCode.self, from: data_)
                UserRegistionViewController.verifyCode = verifyCode
                self?._onGotPhoneVerifyCode()
            } catch {
                sself.view.makeToast(error.localizedDescription)
            }
        }) { [weak self] (error) in
            guard let sself = self else { return }
            sself.view.hideToastActivity()
            sself.view.makeToast(error?.networkErrorMessage ?? Strings.logonFailedSendPhoneCode)
        }
    }
    
    // 获取验证码的后处理流程
    func _onGotPhoneVerifyCode() {
        // TODO: 获取验证码的后处理流程
    }
    
    // 下一步
    @objc func _step2Next() {
        // 校验参数
        let cs: CharacterSet = CharacterSet.whitespacesAndNewlines
        let invitCode: String? = invitCodeTextfield.text?.trimmingCharacters(in: cs)
        guard let mobile = phoneTextfield.text?.trimmingCharacters(in: cs), !mobile.isEmpty,
            let plaintextCode = verifyCodeTextfield.text, !plaintextCode.isEmpty else {
                view.makeToast(Strings.logonPhoneCodeEmpty)
                return
        }
        guard let verifyCode = UserRegistionViewController.verifyCode,
            verifyCode.code == plaintextCode.md5() else {
                view.makeToast(Strings.logonVerifyCodeWrong)
                return
        }
        
        // 注册用户
        let setpwdVC = UserSetPasswordViewController()
        setpwdVC.backCallback = { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
        setpwdVC.onSettedupBlock = { [weak self] newPassword in
            let setnameVC = UserSetUsernameViewController()
            setnameVC.backCallback = { [weak self] in
                self?.navigationController?.popViewController(animated: true)
            }
            setnameVC.onSettedupBlock = { newUsername in
                UserManager.manager.register(
                    mobile: mobile,
                    code: plaintextCode,
                    password: newPassword,
                    username: newUsername,
                    invitCode: invitCode) { [weak self] error in
                        if error == nil {
                            // 注册成功
                            self?.navigationController?.topViewController?.view.makeToast(
                            Strings.logonSuccessRegister) { _ in
                                self?.successCallback()
                            }
                        } else {
                            // 注册失败
                            self?.navigationController?.topViewController?.view.makeToast(
                                error?.networkErrorMessage ?? Strings.logonFailedRegister)
                        }
                }
            }
            self?.navigationController?.pushViewController(setnameVC, animated: true)
        }
        navigationController?.pushViewController(setpwdVC, animated: true)
    }
}
